package com.data.permission.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @包名称 com.thrift.distributed.utils
 * @类描述 <pre> 获取本机IP地址</pre>
 * @作者 zhangbo
 * @创建时间 2019/9/19
 * @版本 1.00
 * @修改记录 <pre>
 *     版本           修改人         修改日期         修改内容描述
 *     -----------------------------------------------------------
 *     1.00           Lenovo        2019/9/19
 *     -----------------------------------------------------------
 * </pre>
 */
@Slf4j
public class NetAddressUtil {

    private NetAddressUtil() {
    }

    public static String getServerIp() {
        String serverIp = null;
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = netInterfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (address instanceof Inet6Address) {
                        continue;
                    }
                    if (address.isSiteLocalAddress() && !address.isLoopbackAddress()) {
                        serverIp = address.getHostAddress();
                        log.debug("获取到本机IP地址：{}", serverIp);
                        return serverIp;
                    }
                }
            }
        } catch (SocketException e) {
            log.error("获取服务器IP地址错误");
        }
        return serverIp;
    }

}
